package com.zyx.netty.codec;

import com.zyx.constants.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.zyx.constants.Constants.*;


/**
 * 描述说明:
 *
 * @author DQing
 * @version 1.0
 * @className RequestHttpDecoder
 * @date 2020/3/26 15:44
 */
@Slf4j
@Component
public class RequestHttpDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        
        ChannelPipeline pipeline = ctx.pipeline();
        String buf = byteBuf.toString(CharsetUtil.UTF_8);
        log.info("#接收客户端请求报文：{}",buf);
        if(buf.startsWith(PROTOCOL_RESPONSE)){
            DynamicHttpCodec.requestHandler(pipeline,false);
        }else if(buf.startsWith(HTTP_METHOD_POST)||buf.startsWith(HTTP_METHOD_GET)){
            DynamicHttpCodec.requestHandler(pipeline,true);
        }
        ByteBuf frame = byteBuf.retainedDuplicate();
        list.add(frame);
        byteBuf.skipBytes(byteBuf.readableBytes());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
